part of '../repository.dart';

const _kInbuiltCollectionTypeValue = 'inbuilt_collection';

class _InbuiltCollectionDto extends Equatable
    implements _InbuiltCollectionListItemDto, _CollectionDto {
  const _InbuiltCollectionDto({
    required this.id,
    required this.titles,
    required this.lexicalItemIds,
    required this.selected,
    required this.highPriority,
    required this.sortingDto,
  });

  @override
  final String id;

  @override
  final BuiltMap<String, String> titles;

  @override
  final BuiltSet<String> lexicalItemIds;

  @override
  final bool selected;

  @override
  final bool highPriority;

  @override
  final _CollectionSortingDto sortingDto;

  @override
  String get type => _kInbuiltCollectionTypeValue;

  @override
  List<Object?> get props {
    return [
      id,
      titles,
      lexicalItemIds,
      selected,
      highPriority,
      sortingDto,
    ];
  }

  factory _InbuiltCollectionDto.fromJson(Map<String, dynamic> json) {
    final titleMap = json[_kInbuiltCollectionListItemTitlesKey] as Map;

    final titles = titleMap.map((languageCode, title) {
      return MapEntry(languageCode as String, title as String);
    }).build();

    final lexicalItemIds = BuiltSet<String>.from(json[_kCollectionLexicalItemIdsKey]);

    final sortingDto = _CollectionSortingDto.fromString(json[_kCollectionSortingKey]);

    return _InbuiltCollectionDto(
      id: json[_kCollectionListItemIdKey],
      titles: titles,
      lexicalItemIds: lexicalItemIds,
      selected: json[_kCollectionSelectedKey],
      highPriority: json[_kCollectionHighPriorityKey],
      sortingDto: sortingDto,
    );
  }

  factory _InbuiltCollectionDto.fromEntity(InbuiltCollection collection) {
    final sortingDto = _CollectionSortingDto.fromEntity(collection.sorting);

    return _InbuiltCollectionDto(
      id: collection.id,
      titles: collection.titles,
      lexicalItemIds: collection.lexicalItemIds,
      selected: collection.selected,
      highPriority: collection.highPriority,
      sortingDto: sortingDto,
    );
  }

  @override
  Map<String, dynamic> toJson() {
    return {
      _kCollectionListItemTypeKey: type,
      _kCollectionListItemIdKey: id,
      _kInbuiltCollectionListItemTitlesKey: titles.toMap(),
      _kCollectionLexicalItemIdsKey: lexicalItemIds.toList(),
      _kCollectionSelectedKey: selected,
      _kCollectionHighPriorityKey: highPriority,
      _kCollectionSortingKey: sortingDto.toString(),
    };
  }

  @override
  InbuiltCollection toEntity() {
    return InbuiltCollection(
      id: id,
      titles: titles,
      lexicalItemIds: lexicalItemIds,
      selected: selected,
      highPriority: highPriority,
      sorting: sortingDto.toEntity(),
    );
  }
}
